<script lang="ts" setup>
import { ref, onMounted, reactive, watch, onUnmounted } from 'vue'
import { storeToRefs } from "pinia";
import { requestGetSoundSource, requestLyric, requestPrivateFM, requestSongListHotCom, requestSongAllCom } from "../../utils/axiosURL";
import useSongURLStore from "../../store/songURL";
import lyricTime from "../../store/lyricTime";
import indexText from "./index.json"
const { lyrics } = storeToRefs(lyricTime())
const songURLStore = useSongURLStore()

// 私人Fm数据
const PrivateFm = reactive<any>([])
// 存储id
let musicID = ref<number>(0)
// fm 数据下标
let privateIndex = ref<number>(0)
// 存储歌词
let transArr = ref<any>([])
let resultLyrics = ref<any>([])
let itemArr = ref<any>([])
let mm = ref<number>(0)
let ss = ref<number>(0)
let time = ref<number>(0)
// 获取歌词滚动容器用于滚动
let LyricsWrapExample = ref<any>(null)
// 获取歌词ul容器的dom实例
let lyricUlExample = ref<any>(null)
// 播放到那一句歌词
let playLyricIndex = ref<number>(0)
// emoji显示状态
let emojiShowState = ref<boolean>(false)
// emoji容器实例
const emojiExample = ref<any>(null)
// 文本域内容
let ctnTextArea = ref<string>('')
// 推荐文案实例
const copyWritingExample = ref<any>(null)
// 推荐文案容器实例
let copyWritingState = ref<any>(false)
// prompt 组件显示状态
let promptState = ref<any>(false)
// 清除定时器
let timer = ref<any>(null)
// 存储热门评论
const saveHotCommentData = reactive<any>([])
// 热门评论总数
const hotCommentTotal = ref<any>(null)
// 请求歌单所有评论的页码
let allCommentPage = ref<any>(1)
// 存储所有歌单评论
let saveAllCommentData = reactive<any>([])
// 所有评论的长度
const allCommentLength = ref<any>(0)

// 切换emoji容器的显示状态
const changeEmojiFn = () => {
  copyWritingState.value = false
  emojiShowState.value = !emojiShowState.value
}
// 拿取emoji
const getEmoji = (index: number) => ctnTextArea.value += emojiExample.value.children[index].innerHTML
// 文案点击事件函数
const copyWritingFn = (index: number) => ctnTextArea.value += copyWritingExample.value.children[index].innerHTML
// 切换推荐文案容器状态
const changeCopyWritingFn = () => {
  emojiShowState.value = false
  copyWritingState.value = !copyWritingState.value
}
// 提交评论事件处理函数
const submitCommentFn = () => {
  if (ctnTextArea.value === '') {
    promptState.value = true
    clearTimeout(timer)
    timer = setTimeout(() => { promptState.value = false }, 1500)
  }
}
//  请求私人FM
const requestPrivateFMFn = () => {
  requestPrivateFM().then(({ data }: any) => {
    PrivateFm.values = data
    musicID.value = data[privateIndex.value].id
    // 请求歌词
    requestLyricFn(data[privateIndex.value].id)
    // 请求热评
    requestSongAllComFn(data[privateIndex.value].id)
    requestSongListHotComFn(data[privateIndex.value].id)
    localStorage.setItem("playState", "false")
    songURLStore.playStateChange(false)
    requestGetSoundSource(data[privateIndex.value].id).then((data2: any) => {
      songURLStore.init(
        data2.data[0].url,
        data[privateIndex.value].name,
        data[privateIndex.value].album?.artists[0].name,
        PrivateFm.values[privateIndex.value]?.album?.picUrl,
        data2.data[0].time,
        privateIndex.value,
        data[privateIndex.value].id
      )
      localStorage.setItem('songInfomation', JSON.stringify(
        {
          songName: data[privateIndex.value].name,
          songUrl: data2.data[0].url,
          singer: data[privateIndex.value].album?.artists[0].name,
          picUrl: PrivateFm.values[privateIndex.value]?.album?.picUrl,
          duration: data2.data[0].time,
          index: privateIndex.value,
          id: data[privateIndex.value].id
        }
      ))
    }).catch(_ => { })
  }).catch(_ => { })
}
// 请求歌词
const requestLyricFn = (id: number) => {
  requestLyric(id).then((data: any) => {
    transArr.value = data.lrc.lyric.split('\n')
    transArr.value.forEach((item: string) => {
      itemArr.value = item.split('[')[1].split(']')
      mm.value = parseInt(itemArr.value[0].split(":")[0])
      ss.value = parseInt(itemArr.value[0].split(":")[1])
      time.value = mm.value * 60 + ss.value
      resultLyrics.value.push({ time: time.value, ly: itemArr.value[1] })
    })
  }).catch(_ => { })
}
// 下一曲事件处理函数
const FMNextFn = () => {
  if (privateIndex.value >= 2) return privateIndex.value = 0
  privateIndex.value++
}
watch(privateIndex, () => {
  transArr.value = []
  resultLyrics.value = []
  itemArr.value = []
  mm.value = 0
  ss.value = 0
  time.value = 0
  requestPrivateFMFn()
})
watch(lyrics, () => {
  LyricsWrapExample.value.forEach((item: any, index: number) => {
    if (item.className === 'lyricActive') {
      playLyricIndex.value = index
    }
  })
})
watch(playLyricIndex, () => {
  if (playLyricIndex.value === 0) return lyricUlExample.value.srollTop = 0
  lyricUlExample.value.scrollTop = (lyricUlExample.value.scrollHeight / resultLyrics.value.length) * playLyricIndex.value
})
// 请求歌曲的热门评论
const requestSongListHotComFn = (id: string) => {
  requestSongListHotCom(id, 0, 0).then((data: any) => {
    saveHotCommentData.values = data.hotComments
    hotCommentTotal.value = data.total
  }).catch(_ => { })
}
// 请求歌曲的所有评论
const requestSongAllComFn = (id: number) => {
  requestSongAllCom(id, allCommentPage.value).then((data: any) => {
    saveAllCommentData.values = data.comments
    allCommentLength.value = data.total
  }).catch(_ => { })
}
const changePages = () => {
  requestSongAllComFn(musicID.value)
}
onMounted(() => {
  requestPrivateFMFn()
})
// 监听页面点击事件隐藏emoji容器
window.addEventListener('click', () => emojiShowState.value = copyWritingState.value = false)
onUnmounted(() => {
  // 销毁事件
  window.removeEventListener('click', () => { })
})
</script>


<template>
  <div class="FMWrap">
    <div class="FMWrapCenter">
      <div class="imgAndLyrics">
        <div class="leftFMImg">
          <div class="centerWrap">
            <img :src="PrivateFm.values[privateIndex]?.album?.picUrl" alt="">
            <div class="more">
              <div class="like">
                <span class="iconfont icon-xihuan"></span>
              </div>
              <div class="delete">
                <span class="iconfont icon-icon"></span>
              </div>
              <div class="next" @click="FMNextFn">
                <span class="iconfont icon-xiayiqu"></span>
              </div>
              <div class="mores">
                <span class="iconfont icon-danlieliebiao"></span>
              </div>
            </div>
          </div>
        </div>
        <div class="rightLyrics">
          <P class="songName">{{ PrivateFm.values[privateIndex]?.name }}</P>
          <p class="assistant">{{ PrivateFm.values[privateIndex]?.transName }}</p>
          <p class="albumAndAuthor">
            <span>
              专辑:
              <RouterLink :to="{
                path: `/AlbumDetail/${PrivateFm.values[privateIndex]?.album?.id}`,
                query: {
                  url: PrivateFm.values[privateIndex]?.album?.picUrl,
                  name: PrivateFm.values[privateIndex]?.album?.name,
                  time: PrivateFm.values[privateIndex]?.album?.publishTime,
                  singerName: PrivateFm.values[privateIndex]?.album?.artists[0].name
                }
              }">
                {{ PrivateFm.values[privateIndex]?.album?.name }}
              </RouterLink>
            </span>
            <span>
              作者:
              <RouterLink :to="`/SingerDetail/${PrivateFm.values[privateIndex]?.artists[0].id}`">
                {{ PrivateFm.values[privateIndex]?.album?.artists[0].name }}
              </RouterLink>
            </span>
          </p>
          <ul ref="lyricUlExample">
            <li ref="LyricsWrapExample"
              v-for="item in resultLyrics.map((item2: any, index2: number) => item2 = { ...item2, end: resultLyrics[index2 + 1]?.time - 1 })"
              :class="lyrics >= item.time && lyrics <= item.end ? 'lyricActive' : ''">{{ item.ly }}</li>
          </ul>
        </div>
      </div>
      <div class="commentWrap">
        <div class="textArea">
          <textarea v-model="ctnTextArea" maxlength="140"></textarea>
        </div>
        <div class="moreWrap">
          <div class="leftWrap">
            <span class="iconfont icon-smile" :class="`${emojiShowState ? 'activeColor' : ''}`"
              @click.stop="changeEmojiFn"></span>
            <span class="iconfont icon-aite"></span>
            <span class="iconfont icon-hash" :class="`${copyWritingState ? 'activeColor' : ''}`"
              @click.stop="changeCopyWritingFn"></span>
          </div>
          <div class="rightWrap">
            <button @click="submitCommentFn">评论</button>
          </div>
          <div v-if="emojiShowState" class="emoji" ref="emojiExample">
            <span v-for="(item, index) in indexText.emoji" @click.stop="getEmoji(index)">{{ item }}</span>
          </div>
          <div class="recommendedCopy" v-if="copyWritingState">
            <p class="RecommendForYou">为你推荐</p>
            <ul ref="copyWritingExample">
              <li v-for="(item, index) in indexText.recommendCopy" @click="copyWritingFn(index)">{{ item }}</li>
            </ul>
          </div>
        </div>
      </div>
      <div class="hotCommentList">
        <p class="excellentComment">精彩评论</p>
        <commentItem v-if="saveHotCommentData.values.length" :commentData=saveHotCommentData.values />
        <commentItemSkeleton v-else v-for="item in 10" />
      </div>
      <div class="allCommentList">
        <p class="allComTitle">全部评论</p>
        <commentItem v-if="saveAllCommentData.values.length" :commentData=saveAllCommentData.values />
        <commentItemSkeleton v-else v-for="item in 10" />
        <div class="paging">
          <el-pagination small background layout="prev, pager, next" :total="allCommentLength"
            v-model:current-page="allCommentPage" @current-change="changePages" />
        </div>
      </div>
      <prompt v-if="promptState" :content=indexText.errorText :type=indexText.errorType />
    </div>
  </div>
</template>


<style lang="scss" scoped>
.FMWrap {
  position: relative;
  @extend .pageWrapSize;

  .FMWrapCenter {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 700px;
    padding-bottom: 40px;
    box-sizing: border-box;

    .imgAndLyrics {
      display: flex;
      width: 100%;
      height: 520px;

      .leftFMImg {
        position: relative;
        flex-basis: 300px;
        width: 50%;
        height: 100%;

        .centerWrap {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          margin: auto;
          width: 300px;
          height: 380px;

          img {
            width: 300px;
            height: 300px;
          }

          .more {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            height: 50px;

            .like,
            .delete,
            .next,
            .mores {
              position: relative;
              width: 40px;
              height: 40px;
              border-radius: 25px;
              border: 1px solid $lineColor;
              text-align: center;

              span {
                line-height: 40px;
                font-size: 24px;
                color: $font_second_color;
              }

              &:hover {
                background-color: $BK_GRAY;
              }
            }
          }
        }
      }

      .rightLyrics {
        flex: 1;
        height: 100%;
        padding: 40px 0;
        margin-left: 30px;
        box-sizing: border-box;

        .songName {
          font-size: $font-size-lg2;
          color: $font_main_color;
          font-family: $textFont;
          margin-bottom: 6px;
        }

        .assistant {
          font-size: $font-size-xs;
          color: $font_main_color;
          font-family: $textFont;
          margin-bottom: 6px;
        }

        .albumAndAuthor {
          display: flex;
          font-size: $font-size-xs;
          color: $font_main_color;
          font-family: $textFont;

          span {
            margin-right: 40px;

            a {
              color: cornflowerblue;
            }
          }
        }

        ul {
          scroll-behavior: smooth;
          width: 100%;
          height: 390px;
          padding-bottom: 180px;
          padding-top: 180px;
          box-sizing: border-box;
          overflow: auto;
          border-right: 1px solid $lineColor;

          li {
            color: $font_second_color;
            font-family: $activeTextFont;
            margin-bottom: 20px;
          }

          .lyricActive {
            font-size: 24px;
            @include author_color('author_color');
          }
        }
      }
    }

    .commentWrap {
      width: 100%;
      height: 120px;

      .textArea {
        position: relative;
        width: 100%;
        height: 80px;

        textarea {
          width: 100% !important;
          height: 100% !important;
          padding: 4px 8px;
          outline: none;
          border: 1.5px solid $lineColor;
          box-sizing: border-box;
          border-radius: $borderRadius8;
          font-size: $font-size-xs;
          font-family: $textFont;
        }

        &::before {
          content: "140";
          position: absolute;
          right: 3px;
          bottom: 3px;
          width: 20px;
          font-size: $font-size-xs;
          font-family: $textFont;
          color: $font_second_color;
          background: #fff;
        }
      }

      .moreWrap {
        position: relative;
        display: flex;
        width: 100%;
        height: 40px;

        .leftWrap {
          flex-basis: 90px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          span {
            color: $font_second_color;
            font-size: $font-size-lg;

            &:hover {
              color: $font_main_color;
            }
          }

          .activeColor {
            color: $font_second_color !important;
          }
        }

        .rightWrap {
          flex: 1;
          display: flex;
          justify-content: end;
          align-items: center;

          button {
            @extend .clearButton;
            width: 60px;
            height: 30px;
            border-radius: 25px;
            border: 1px solid $lineColor;
          }
        }

        .emoji {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          position: absolute;
          top: 40px;
          left: 0;
          width: 375px;
          padding: 8px;
          box-sizing: border-box;
          box-shadow: 0px 0px 8px 0px rgb(230, 230, 230);
          border-radius: 6px;
          background-color: #fff;

          span {
            margin: 0 10px 10px 0;
          }

          &::after {
            content: "×";
            position: absolute;
            top: 0;
            right: 0;
            width: 20px;
            height: 20px;
            text-align: center;
            color: $font_second_color;
          }
        }

        .recommendedCopy {
          position: absolute;
          top: 40px;
          left: 72px;
          width: 285px;
          box-shadow: 0px 0px 8px 0px rgb(230, 230, 230);
          border-radius: 6px;
          background-color: #fff;

          .RecommendForYou {
            color: $font_second_color;
            font-size: $font-size-sm;
            padding-left: 15px;
            box-sizing: border-box;
            line-height: 35px;
            box-shadow: 0px 1px 2px 0 rgb(230, 230, 230);
          }

          ul {
            li {
              color: $font_second_color;
              font-size: $font-size-sm;
              padding-left: 15px;
              box-sizing: border-box;
              line-height: 35px;

              &:nth-child(1) {
                background-color: rgb(250, 250, 250);
              }

              &:hover {
                background-color: rgb(250, 250, 250);
              }
            }
          }
        }
      }
    }

    .hotCommentList {
      width: 100%;
      margin-top: 10px;

      .excellentComment {
        font-family: $activeTextFont;
      }

      .viewMore {
        display: flex;
        justify-content: center;
        margin-top: 40px;

        button {
          @extend .clearButton;
          border: 1px solid $lineColor;
          padding: 6px 20px;
          border-radius: 25px;
          cursor: pointer;
          font-size: $font-size-sm;

          span {
            vertical-align: -1px;
            font-size: $font-size-sm;
          }
        }
      }
    }

    .allCommentList {
      width: 100%;
      margin-top: 50px;

      .allComTitle {
        font-family: $activeTextFont;
      }

      .paging {
        display: flex;
        justify-content: center;
        width: 100%;
        margin-top: 50px;

        :deep(.number) {
          border-radius: 4px;
          font-family: none;
          font-family: $textFont;
          background-color: transparent;
          border: 1px solid $lineColor;

          &:hover {
            color: $font_main_color;
            background-color: $BK_GRAY;
          }
        }

        :deep(.is-active) {
          background-color: $theme-red;
          border-radius: 4px;

          &:hover {
            color: $theme-white;
            background-color: $theme-red;
          }
        }

        :deep(.btn-prev),
        :deep(.btn-next) {
          border-radius: 4px;
          border: 1px solid $lineColor;
          background-color: transparent;

          &:hover {
            color: $font_red_color;
            background-color: $BK_GRAY;
          }
        }

        :deep(.more) {
          border-radius: 4px;
          border: 1px solid $lineColor;
          background-color: transparent;

          &:hover {
            color: $font_red_color;
            background-color: $BK_GRAY;
          }
        }
      }
    }
  }
}
</style>
